<?php

namespace app\admin\controller\work;

use app\common\controller\Backend;
use app\common\model\work\Service;
use app\common\model\work\Warranty as WarrantyModel;
use app\common\model\Workflow;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 报价管理
 *
 * @icon fa fa-circle-o
 */
class Offer extends Backend
{

    /**
     * Offer模型对象
     * @var \app\common\model\work\Offer
     */
    protected $model = null;
    protected $searchFields = 'warranty.workID,warranty.product,name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\work\Offer;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['warranty'])
                    ->field("a.name 'a.name',a.marking 'a.marking'")
                    ->join("equipment a","a.id=warranty.equipment_id",'left')
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('warranty')->visible(['product','device','workID']);
                /*$row->substance=json_decode($row->substance,true);
                $str='';
                foreach ($row->substance as $k=>$v){
                    if($k==0){
                        $str.="<div><p style='text-align: left;'> 名称:".$v["name"]." </p><p style='text-align: left;'>报价：".$v["money"]."   数量:".$v["number"]."</p>";
                    }else{
                        $str.="<hr><p style='text-align: left;'>名称:".$v["name"]."</p><p style='text-align: left;'>报价：".$v["money"]."   数量:".$v["number"]."</p>";
                    }
                }
                $str.="</div>";
                $row->substance=$str;*/
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        $ids=$this->request->param("ids");
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                $warranty=WarrantyModel::where(["id"=>$ids])->find();
                if($warranty["type_data"]==1){
                    //维保
                    $service=Service::where(["warranty_id"=>$ids])->where("status != '3'")->order("servicetime")->find();
                }else{
                    $service=Service::where(["warranty_id"=>$ids])->find();
                }
                if(empty($service)) $this->error("该工单不能填写报价");
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params["warranty_id"]=$ids;
                    $time=time();
                    $params["createtime"]=$time;
                    if(!empty($params["image"]) && !strstr($params["image"],"http")) $params["image"]=$this->request->domain().$params["image"];
                    $result = $this->model->allowField(true)->insertGetId($params);
                    /******************添加工作流  start  待完成******************************/
                    $workflow=array(
                        "warranty_id"=>$ids,//工单id
                        "hospital_id"=>$warranty["hospital_id"],//医院id
                        "user_id"=>0,//用户id
                        "type_data"=>1,//类型:0=成本,1=报价,2=方案,3=维修,4=勘察记录,5=保养,6=申请结单,7=平台,8=创建维修单
                        "type_id"=>$result,//类型id
                        "title"=>"更新了报价",//标题
                        "content"=>$params["money"],//详情
                        "images"=>$params["image"],//图片
                        "createtime"=>$time,//创建时间
                    );
                    if($warranty["type_data"]==1){
                        $workflow["service_id"]=$service["id"];
                        $workflow["number"]=$service["number"];
                        $workflow["types_data"]=1;
                    }
                    Workflow::create($workflow);
                    /******************添加工作流  end******************************/
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
}
